package com.mycase.im.boot.websocket.pattern.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mycase.im.boot.entity.communication.ClientMessage;
import com.mycase.im.boot.entity.communication.ResponseMessage;
import com.mycase.im.boot.entity.database.ImChatGroup;
import com.mycase.im.boot.entity.database.ImChatGroupUser;
import com.mycase.im.boot.service.ChatGroupService;
import com.mycase.im.boot.service.ChatGroupUserService;
import com.mycase.im.boot.service.MessageService;
import com.mycase.im.boot.websocket.WebSocketSignal;
import com.mycase.im.boot.websocket.pattern.MessageStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.websocket.Session;
import java.util.List;
import java.util.Map;

/**
 * 用来通知群聊的创建
 * @Author ZhuHJay
 * @Date 2021/9/18 21:19
 */
@Slf4j
@Service
public class CreatedGroup implements MessageStrategy {

    @Autowired
    private ChatGroupService chatGroupService;
    @Autowired
    private ChatGroupUserService chatGroupUserService;
    @Autowired
    private MessageService messageService;

    @Override
    public Boolean isUse(int type) {
        return WebSocketSignal.MESSAGE_GROUP_CREATE == type;
    }

    @Override
    public void executeHandler(ClientMessage clientMessage,
                               ObjectMapper objectMapper,
                               Map<String, Session> clientMaps,
                               Session mySession) throws Exception {
        log.warn("onMessage -匹配到-> CreatedGroup(群聊创建)");

        // 通过群聊的id获取群的信息
        ImChatGroup chatGroupInfo = chatGroupService.getById(clientMessage.getGroupId());
        // 获取群聊的额外信息(群成员)
        List<ImChatGroupUser> groupUserList = chatGroupUserService.getGroupUserListById(chatGroupInfo.getId());
        chatGroupInfo.setGroupUsers(groupUserList);
        // 聊天记录按需生成(每一个人都需要, 但是如果在线才生成, 因为消息体是独立用户拥有的)
        // 接下来开始发送消息给客户端了
        for (ImChatGroupUser user : groupUserList) {
            // 判断如果用户在线
            if( clientMaps.containsKey(user.getUserId()) ){
                // 查询该用户的聊天记录
                messageService.getGroupMessageRecord(user.getUserId(), chatGroupInfo);
                // 然后发送出去
                sendMessage(objectMapper, clientMaps.get(user.getUserId()),
                            ResponseMessage.success()
                                    .appendData("type", WebSocketSignal.MESSAGE_GROUP_CREATE)
                                    .appendData("groupInfo", chatGroupInfo)
                );
            }
        }
    }
}
